package cn.mifengkong.appcommon.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRString;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by jiangyongxing on 2017/5/22.
 * 描述：
 */

public class ClassUtil {


    private final static String TAG = "ClassUtils";

    private ClassUtil() {
    }

    /**
     * 返回AndroidManifest.xml中注册的所有Activity的class
     *
     * @param context     环境
     * @param packageName <span style="white-space:pre">       </span>包名
     * @return
     */
    public static List<Class> getActivitiesClass(Context context, String packageName) {

        List<Class> returnClassList = new ArrayList<>();
        try {
            //Get all activity classes in the AndroidManifest.xml
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            if (packageInfo.activities != null) {
                for (ActivityInfo ai : packageInfo.activities) {
                    Class c;
                    try {
                        c = Class.forName(ai.name);
                        // Maybe isAssignableFrom is unnecessary
                        if (Activity.class.isAssignableFrom(c)) {
                            returnClassList.add(c);
                            FRLog.debug(ai.name + "...OK");
                        }
                    } catch (ClassNotFoundException e) {
                        FRLog.debug("Class Not Found:" + ai.name);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return returnClassList;
    }

    public static Class getClassByName(Context context, String packageName, String activityName) {
        if (FRString.isEmpty(activityName)) {
            return null;
        }
        List<Class> classList = getActivitiesClass(context, packageName);
        for (Class aClass : classList) {
            if (aClass.toString().contains(activityName)) {
                return aClass;
            }
        }
        return null;
    }
}
